package com.example.lenovo.asia5b.home.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.lenovo.asia5b.commodity.activity.CommodityDetActivity;
import com.example.lenovo.asia5b.home.bean.UserBean;
import com.example.lenovo.asia5b.home.fragment.MainNewProductsFragment;
import com.example.lenovo.asia5b.home.fragment.MianHomeFragment;
import com.example.lenovo.asia5b.home.fragment.MianMyA5bFragment;
import com.example.lenovo.asia5b.home.fragment.MianShopingCartFragment;
import com.example.lenovo.asia5b.my.bean.TestBean;
import com.example.lenovo.asia5b.ui.PublicDialog;
import com.example.lenovo.asia5b.util.AppInnerDownLoder;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.MobileInfoUtils;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.SharedPrefereLoginUtils;
import com.example.lenovo.asia5b.util.SharedPreferencesUtils;
import com.example.lenovo.asia5b.util.keyboardUtil;
import com.mob.moblink.Scene;
import com.mob.moblink.SceneRestorable;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import app.BaseActivity;
import app.MyApplication;
import fay.frame.ui.U;

import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;


public class MainActivity extends BaseActivity implements ICallBack,SceneRestorable {
    private RelativeLayout rl_home, rl_new, rl_shoping_cart, rl_my_a5b;
    private TextView txt_home, txt_new, txt_shoping_cart, btn_my_a5b, txt_customer_service;
    private ImageButton image_home, image_new, image_shoping_cart, image_my_a5b;
    public int currentIndex;// 当前选中
    public int previousIndex;
    public int sumIndexs = 4;// 总数
    private PublicDialog mDialog;
    /**
     * 用于对Fragment进行管理
     */
    private FragmentManager fragmentManager;
    private Fragment MianHomeFragment, MainNewProductsFragment,
            MianShopingCartFragment, MianMyA5bFragment;

    //保存用户提示
    private SharedPreferences languagePre;
    private final String START = "START";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        updateData();
        isaloneData();
        savaShareIco();
        clipboard();
        hintData();
        //用户第一次用项目就弹出提示用户
        languagePre = getSharedPreferences("main",
                Context.MODE_PRIVATE);
        boolean isStart = languagePre.getBoolean(START,false );
        if (!isStart) {
//            startDia();
        }
        SharedPrefereLoginUtils.setBeanList(getUserBean());
        if (!TextUtils.isEmpty(MyApplication.goodsId)){
            Intent intent = new Intent(MainActivity.this, CommodityDetActivity.class);
            intent.putExtra("goods_id",MyApplication.goodsId);
            startActivity(intent);
        }
        MyApplication.goodsId = "";
    }

    private void initView() {
        rl_home = (RelativeLayout) findViewById(R.id.rl_home);
        rl_new = (RelativeLayout) findViewById(R.id.rl_new);
        rl_shoping_cart = (RelativeLayout) findViewById(R.id.rl_shoping_cart);
        rl_my_a5b = (RelativeLayout) findViewById(R.id.rl_my_a5b);

        txt_home = (TextView) findViewById(R.id.txt_home);
        txt_new = (TextView) findViewById(R.id.txt_new);
        txt_shoping_cart = (TextView) findViewById(R.id.txt_shoping_cart);
        btn_my_a5b = (TextView) findViewById(R.id.txt_my_a5b);

        image_home = (ImageButton) findViewById(R.id.btn_home);
        image_new = (ImageButton) findViewById(R.id.btn_new);
        image_shoping_cart = (ImageButton) findViewById(R.id.btn_shoping_cart);
        image_my_a5b = (ImageButton) findViewById(R.id.btn_my_a5b);

        rl_home.setOnClickListener(this);
        rl_new.setOnClickListener(this);
        rl_shoping_cart.setOnClickListener(this);
        rl_my_a5b.setOnClickListener(this);
        fragmentManager = getSupportFragmentManager();
        if (getIntent().hasExtra("selection")) {
            setTabSelection(getIntent().getIntExtra("selection", 0));
        } else {
            setTabSelection(0);
        }
    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.rl_home:
                previousIndex = 0;
                setTabSelection(0);
                keyboardUtil.HideKeyboard(rl_home);
                break;
            case R.id.rl_new:
                previousIndex = 1;
                setTabSelection(1);
                keyboardUtil.HideKeyboard(rl_home);
                break;
            case R.id.rl_shoping_cart:
                previousIndex = 2;
                setTabSelection(2);
                keyboardUtil.HideKeyboard(rl_home);
                break;
            case R.id.rl_my_a5b:
                previousIndex = 3;
                setTabSelection(3);
                keyboardUtil.HideKeyboard(rl_home);
                break;
            default:
                break;
        }
    }


    /**
     * 根据传入的index参数来设置选中的tab页。
     */

    public void setTabSelection(int index) {
//        closePraiseGuide();
        currentIndex = index;
        // 重置按钮
        resetBtn();

        changBootUI();
        // 开启一个Fragment事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(transaction);
        UserBean userBean = (UserBean) SharedPreferencesUtils.getObjectFromShare("user");
        Intent intent = null;
        switch (index) {
            case 0:
                if (MianHomeFragment == null) {
                    // 如果MessageFragment为空，则创建一个并添加到界面上
                    MianHomeFragment = new MianHomeFragment();
                    transaction.add(R.id.id_content, MianHomeFragment);
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(MianHomeFragment);
                }
                break;
            case 1:
                if (MainNewProductsFragment == null) {
                    // 如果MessageFragment为空，则创建一个并添加到界面上
                    MainNewProductsFragment = new MainNewProductsFragment();
                    transaction.add(R.id.id_content, MainNewProductsFragment);
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(MainNewProductsFragment);
                }
                break;
            case 2:
                if (userBean == null) {
                    intent = new Intent(this, LoginActivity.class);
                    startActivityForResult(intent,300);
                } else {
                    if (MianShopingCartFragment == null) {
                        // 如果MessageFragment为空，则创建一个并添加到界面上
                        MianShopingCartFragment = new MianShopingCartFragment();
                        transaction.add(R.id.id_content, MianShopingCartFragment);
                    } else {
                        // 如果MessageFragment不为空，则直接将它显示出来
                        transaction.show(MianShopingCartFragment);
                    }
                    ((MianShopingCartFragment)MianShopingCartFragment).cartData();
                }
                break;
            case 3:
                if (userBean == null) {
                    intent = new Intent(this, LoginActivity.class);
                    startActivityForResult(intent,300);
                } else {
                    if (MianMyA5bFragment == null) {
                        // 如果NewsFragment为空，则创建一个并添加到界面上
                        MianMyA5bFragment = new MianMyA5bFragment();
                        transaction.add(R.id.id_content, MianMyA5bFragment);
                    } else {
                        // 如果NewsFragment不为空，则直接将它显示出来
                        transaction.show(MianMyA5bFragment);
                    }
                }
                break;
        }
        transaction.commitAllowingStateLoss();
    }


    /**
     * 清除掉所有的选中状态。
     */
    private void resetBtn() {
        image_home.setImageResource(R.drawable.main_home);
        image_new.setImageResource(R.drawable.main_new);
        image_shoping_cart.setImageResource(R.drawable.main_shopping_cart);
        image_my_a5b.setImageResource(R.drawable.main_my_a5b);
        txt_home.setTextColor(getResources().getColor(R.color.my_777));
        txt_new.setTextColor(getResources().getColor(R.color.my_777));
        txt_shoping_cart.setTextColor(getResources().getColor(R.color.my_777));
        btn_my_a5b.setTextColor(getResources().getColor(R.color.my_777));
    }

    private void changBootUI() {
        switch (currentIndex) {
            case 0:
                image_home.setImageResource(R.drawable.main_select_home);
//                txt_home.setTextColor(getResources().getColor(R.color.wathet));
                break;
            case 1:
                image_new.setImageResource(R.drawable.main_select_new);
//                txt_new.setTextColor(getResources().getColor(R.color.wathet));
                break;
            case 2:
                image_shoping_cart.setImageResource(R.drawable.main_select_shopping_cart);
//                txt_shoping_cart.setTextColor(getResources().getColor(R.color.wathet));
                break;
            case 3:
                image_my_a5b.setImageResource(R.drawable.main_select_my_a5b);
//                btn_my_a5b.setTextColor(getResources().getColor(R.color.wathet));
                break;
            default:
                break;
        }
    }

    /**
     * 将所有的Fragment都置为隐藏状态。
     *
     * @param transaction 用于对Fragment执行操作的事务
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (MianHomeFragment != null) {
            transaction.hide(MianHomeFragment);
        }
        if (MainNewProductsFragment != null) {
            transaction.hide(MainNewProductsFragment);
        }
        if (MianShopingCartFragment != null) {
            transaction.hide(MianShopingCartFragment);
        }
        if (MianMyA5bFragment != null) {
            transaction.hide(MianMyA5bFragment);
        }

    }

    @Override
    public void onAttachFragment(Fragment fragment) {
        if (MianHomeFragment == null && fragment instanceof MianHomeFragment)
            MianHomeFragment = fragment;
        if (MainNewProductsFragment == null && fragment instanceof MainNewProductsFragment)
            MainNewProductsFragment = fragment;
        if (MianShopingCartFragment == null && fragment instanceof MianShopingCartFragment)
            MianShopingCartFragment = fragment;
        if (MianMyA5bFragment == null && fragment instanceof MianMyA5bFragment)
            MianMyA5bFragment = fragment;
    }
    //=============================================更新下载==============================================================

    /*
    * 更新下载
     */
    public void updateData() {
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.UPDATE;
            JsonTools.getJsonAll(this, url, parmaMap, 0);
        } catch (Exception e) {
        }
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result = null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                    if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            JSONObject jsonObject = json.getJSONObject("images");
                            //判断网上版本,假如和本地不一样就开始提示用户开始下载
                            if (AppInnerDownLoder.getVerName(MainActivity.this).compareTo(jsonObject.getString("version")) < 0) {
                                String updateurl = jsonObject.getString("apkurl");
                                String upgradeinfo = jsonObject.getString("desc");
                                forceUpdate(MainActivity.this, getResources().getString(R.string.app_name), updateurl, upgradeinfo);
                            }
                        } else if (state == 1) {
                            U.Toast(MainActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(MainActivity.this, getResources().getString(R.string.cscw));
                        }
                    } catch (Exception e) {
                    }
                }
            }else if (action == 1) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            String isalone = json.getString("isalone");
                            if (isalone.equals("-1")) {
                                Intent i = new Intent(MainActivity.this, OtherLoginDialogActivity.class);  //自定义打开的界面
                                startActivity(i);
                            }
                        } else if (state == 1) {
                            U.Toast(MainActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(MainActivity.this, getResources().getString(R.string.cscw));
                        }
                    } catch (Exception e) {
                    }
                }
            }else if (action == 2) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            if (!HolidayDialogActivity.getTwos()) {
                                JSONArray data = json.getJSONArray("data");
                                ArrayList<TestBean> testList = new ArrayList<>();
                                if (data.length() > 0){
                                    for (int i = 0; i < data.length(); i++) {
                                        JSONObject dataObj = (JSONObject) data.get(i);
                                        TestBean testBean = new TestBean();
                                        testBean.setHint_en(dataObj.getString("hint_en"));
                                        testBean.setIdentifying(dataObj.getString("identifying"));
                                        testBean.setMobile_picture(dataObj.getString("mobile_picture"));
                                        testBean.setTitle(dataObj.getString("title"));
                                        testList.add(testBean);
                                    }

                                    Intent intent = new Intent(MainActivity.this, HolidayDialogActivity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable("data",testList);
                                    intent.putExtras(bundle);
                                    startActivity(intent);
                                }

                            }
                        } else if (state == 1) {
                            U.Toast(MainActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(MainActivity.this, getResources().getString(R.string.cscw));
                        }
                    } catch (Exception e) {
                        Log.e("6666666666666666",e.toString());
                    }
                }
            }
        }

    };
    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }


    private void forceUpdate(final Context context, final String appName, final String downUrl, final String updateinfo) {
        if (TextUtils.isEmpty(downUrl)) {
            return;
        }
        mDialog = new PublicDialog(this);
        mDialog.setTitle(getResources().getString(R.string.fxxbb));
        mDialog.setContent(updateinfo);
        mDialog.setLeftButton(getResources().getString(R.string.qx));// 设置按钮
        mDialog.setRightButton(getResources().getString(R.string.ljgx));
        mDialog.setRightButtonClick(new PublicDialog.OnClickListener() {

            @Override
            public void onClick(View v) {
                AppInnerDownLoder.downLoadApk(MainActivity.this,downUrl,appName);
            }
        });
        mDialog.setLeftButtonClick(new PublicDialog.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismissDialog();
            }
        });
        mDialog.showDialog();
    }

    //============================================提示用户去自启用=============================================================

    private void startDia() {
        mDialog = new PublicDialog(this);
        mDialog.setTitle(getResources().getString(R.string.xtts));
        mDialog.setContent(getResources().getString(R.string.app_user_auto_start));
        mDialog.setLeftButton(getResources().getString(R.string.qx));// 设置按钮
        mDialog.setRightButton(getResources().getString(R.string.confirm));
        mDialog.setRightButtonClick(new PublicDialog.OnClickListener() {

            @Override
            public void onClick(View v) {
                MobileInfoUtils.jumpStartInterface(MainActivity.this);
            }
        });
        mDialog.setLeftButtonClick(new PublicDialog.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismissDialog();
            }
        });
        mDialog.showDialog();
        //当弹出窗口后就不会再弹出
        languagePre.edit().putBoolean(START, true).commit();
    }

    @Override
    public void onActivityResult(int requestCode, int arg1, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, arg1, data);
        MianHomeFragment.onActivityResult(requestCode, arg1, data);
        switch (requestCode) {
            case 0:// 相机
                if (null != data) {
                    if (data.hasExtra("shopingCart")) {
                        previousIndex = 3;
                        setTabSelection(3);
                        keyboardUtil.HideKeyboard(rl_home);
                    }
                }
                break;
        }

        switch (arg1) {
            case 300:// 登录返回
                if (null != data) {
                    previousIndex = 0;
                    setTabSelection(0);
                    keyboardUtil.HideKeyboard(rl_home);
                }
                break;
        }
    }

    //=============================================APP是否单独在线==============================================================
    public void isaloneData() {
        if (null == getUserBean()) {
            return;
        }
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.ISALONE;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"user_alias"+ MyApplication.registrationId,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr.toString()));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("user_alias",MyApplication.registrationId);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 1);
        }catch (Exception e) {

        }
    }


    /**
     * 将分享图片保存到文件夹里面
     */
    public void savaShareIco() {
        File dirFile = new File(Setting.IMAGE_ROOTPATH);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        File uploadFile = new File(dirFile + "/"+Setting.SHARE_IMAG_NAME);
        if (uploadFile.exists()) {
            return;
        }
        Resources res = this.getResources();
        BitmapDrawable d = (BitmapDrawable) res.getDrawable(R.drawable.wechat);
        Bitmap img = d.getBitmap();
        try{
            uploadFile.createNewFile();
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(uploadFile));
            img.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        }catch(Exception e){
            Log.e("TAG", "", e);
        }

    }
    //=============================================活动展示==============================================================
    public void hintData() {
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.HINT;
            JsonTools.getJsonAll(this, url, parmaMap, 2);
        }catch (Exception e) {

        }
    }

    @Override
    public void onReturnSceneData(Scene scene) {
        if(null ==scene) {
            // 处理场景还原数据, 更新画面
            U.Toast(MainActivity.this, "22222222222222222222222");
        } else {
            U.Toast(MainActivity.this, scene.toString());
        }
    }

}
